﻿
using Models.Common;
using Models.Device;
using Models.TaskPlain;
using NetTaste;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using static Models.Common.EnumDeviceState;
using GatewayServerService.Data;
using UtilsCache;
using UtilsBase;
using UtilsORM;
using UtilsORM.MySqlData;
using GatewayServerService.CloudCenter;

namespace GatewayServerService.Device
{
    /// <summary>
    /// 中盛-脉冲计数器 8路
    /// </summary>
    public class ServiceDeviceRS4851026_backup
    {
        ServiceCloudDeviceValueLog log = new ServiceCloudDeviceValueLog();
        //回调
        public void callBackUpdate(MQReqModel<object> httpReqModel)
        {
            //收到信息如：01 04 30 00 00 00 00 00 2F 00 00 00 00 00 3E 00 00 00 00 00 4C 00 00 00 00 00 7C 00 00 00 00 00 1A 00 00 00 00 00 12 00 00 00 00 00 0F 00 00 00 00 00 27 CF 89
            //158位
            try
            {
                ModelReceverData modelDeviceData = httpReqModel.toServerData;
                CommandLogModel commandLogModel = httpReqModel.toGatewayData;


                ModelCommandAgreement modelCommandAgreement = JsonConvert.DeserializeObject<ModelCommandAgreement>(commandLogModel.parameter);
                ModelCommandAgreementParameter modelCommandAgreementParameter = UtilsObject.DynamicToEntity<ModelCommandAgreementParameter>(modelCommandAgreement.agreementParameter);
                if (modelDeviceData == null)
                {
                    return;
                }
                string result = modelDeviceData.commandResults[0].value;
                if (commandLogModel.key == "getCount" && !string.IsNullOrWhiteSpace(result))
                {

                    //-------------测试临时注释------------------
                    if (result.Length != 158)
                    {
                        //返回错误的结果
                        return;
                    }

                    string dataHex1 = result.Substring(15, 11);
                    string dataHex2 = result.Substring(33, 11);
                    string dataHex3 = result.Substring(51, 11);
                    string dataHex4 = result.Substring(69, 11);
                    string dataHex5 = result.Substring(87, 11);
                    string dataHex6 = result.Substring(105, 11);
                    string dataHex7 = result.Substring(123, 11);
                    string dataHex8 = result.Substring(141, 11);
                    int[] pulse = new int[9];
                    pulse[1] = new UtilsDataTypeChange().hex16Convert10(dataHex1);
                    pulse[2] = new UtilsDataTypeChange().hex16Convert10(dataHex2);
                    pulse[3] = new UtilsDataTypeChange().hex16Convert10(dataHex3);
                    pulse[4] = new UtilsDataTypeChange().hex16Convert10(dataHex4);
                    pulse[5] = new UtilsDataTypeChange().hex16Convert10(dataHex5);
                    pulse[6] = new UtilsDataTypeChange().hex16Convert10(dataHex6);
                    pulse[7] = new UtilsDataTypeChange().hex16Convert10(dataHex7);
                    pulse[8] = new UtilsDataTypeChange().hex16Convert10(dataHex8);


                    //Console.WriteLine("pulse1:" + pulse1 + "");
                    //Console.WriteLine("pulse2:" + pulse2 + "");
                    //Console.WriteLine("pulse3:" + pulse3 + "");
                    //Console.WriteLine("pulse4:" + pulse4 + "");
                    //Console.WriteLine("pulse5:" + pulse5 + "");
                    //Console.WriteLine("pulse6:" + pulse6 + "");
                    //Console.WriteLine("pulse7:" + pulse7 + "");
                    //Console.WriteLine("pulse8:" + pulse8 + "");

                    //查当次总流量 和历史总流量
                    double currentFlow = 0;
                    double totalFlow = 0;
                    int currentPulse = 0;
                    int totalPulse = 0;
                    int secondPulse = 0;
                    double secondflowSpeed = 0;
                    EFYihongIotContext ef = new EFYihongIotContext();
                    double deviceFactor = 0;//系数
                    double deviceCount = 0;//频率多少次一L


                    //默认设置3.5MM口径
                    deviceFactor = 17.3;
                    deviceCount = 1038.0;

                    //查询8路设备，全部更新 
                    iot_device device = new DBIotDeviceCache().getClientDeviceByCache(commandLogModel.d_guid);
                    List<iot_device> devices = ef.iot_device.Where(c => c.d_model_guid == device.d_model_guid && c.d_gw_d_guid == device.d_gw_d_guid && c.d_status == 0).ToList();
                    foreach (iot_device item in devices)
                    {
                        //判断流量计的口径型号规格



                        ModelCommandAgreement modelCommandAgreementDevice = JsonConvert.DeserializeObject<ModelCommandAgreement>(item.d_parameter);
                        ModelCommandAgreementParameter modelCommandAgreementParameterDevice = UtilsObject.DynamicToEntity<ModelCommandAgreementParameter>(modelCommandAgreementDevice.agreementParameter);
                        if (modelCommandAgreementParameterDevice != null)
                        {
                            if (modelCommandAgreementParameterDevice.explain == "3.5mm")
                            {//3.5MM口径
                                deviceFactor = 17.3;
                                deviceCount = 1038.0;
                            }
                            else if (modelCommandAgreementParameterDevice.explain == "20mm")
                            {
                                //4分管口径
                                deviceFactor = 7.5;
                                deviceCount = 450.0;
                            }
                        }

                        //查当次总流量 和历史总流量
                        currentFlow = 0;
                        totalFlow = 0;
                        currentPulse = 0;
                        totalPulse = 0;
                        secondPulse = 0;
                        secondflowSpeed = 0;
                        List<iot_device_value_current> list = ef.iot_device_value_current.Where(c => c.vc_d_guid == item.d_guid).ToList();
                        if (list.Count > 0)
                        {
                            currentPulse = pulse[(int)item.d_channel];
                            if (pulse[(int)item.d_channel] == 0)
                            {
                                secondPulse = pulse[(int)item.d_channel];

                            }
                            else if (pulse[(int)item.d_channel] > 0)
                            {
                                DateTime dt1 = (DateTime)list.Where(c => c.vc_key == "currentPulse").FirstOrDefault().vc_add_time;
                                DateTime dt2 = DateTime.Now;
                                TimeSpan ts = dt2 - dt1;

                                int getfromCurrentPulse = int.Parse(list.Where(c => c.vc_key == "currentPulse").FirstOrDefault().vc_value);
                                secondPulse = pulse[(int)item.d_channel] - getfromCurrentPulse;
                                if (ts.Seconds == 0)
                                {
                                    return;
                                }
                                secondflowSpeed = secondPulse / ts.Seconds / deviceFactor;


                                if (getfromCurrentPulse == currentPulse)
                                {

                                    //跳过 没有变化
                                    continue;
                                }
                            }



                            //if (item.d_code == "20075")
                            //{
                            //    totalPulse = int.Parse(list.Where(c => c.vc_key == "totalPulse").FirstOrDefault().vc_value) + secondPulse;
                            //    int a = 0;
                            //}
                            //if (item.d_code== "20076")
                            //{
                            //    totalPulse = int.Parse(list.Where(c => c.vc_key == "totalPulse").FirstOrDefault().vc_value) + secondPulse;
                            //    int a = 0;
                            //}
                            //if(secondPulse<0)
                            //{
                            //    int aa = 1;
                            //}

                            int getData_totalPulse = int.Parse(list.Where(c => c.vc_key == "totalPulse").FirstOrDefault().vc_value);
                            totalPulse = getData_totalPulse + secondPulse;
                            currentFlow = pulse[(int)item.d_channel] / deviceCount;
                            totalFlow = totalPulse / deviceCount;

                            if (getData_totalPulse > totalPulse)
                            {
                                //网络问题，会导致前后顺利有点问题,丢弃  //跳过 
                                continue;
                            }

                        }
                        else
                        {
                            secondPulse = 0;
                            totalPulse = pulse[(int)item.d_channel];
                            currentFlow = currentPulse / deviceCount;
                            totalFlow = totalPulse / deviceCount;
                            secondflowSpeed = 0;

                        }
                        Console.WriteLine("currentPulse:" + currentPulse + "");
                        Console.WriteLine("totalPulse:" + totalPulse + "");
                        Console.WriteLine("currentFlow:" + currentFlow + "L");
                        Console.WriteLine("totalFlow:" + secondflowSpeed + "L");

                        //写日志
                        ServiceCloudDeviceValueLog log = new ServiceCloudDeviceValueLog();
                        log.writeSensorlog(item.d_guid, "secondPulse", secondPulse.ToString(), "每秒脉冲数");
                        log.writeSensorlog(item.d_guid, "secondflowSpeed", UtilsNumber.GetNumberForLength(secondflowSpeed, 2).ToString(), "流速L/min");
                        log.writeSensorlog(item.d_guid, "currentPulse", currentPulse.ToString(), "当前持续脉冲数");
                        log.writeSensorlog(item.d_guid, "totalPulse", totalPulse.ToString(), "历史脉冲总数");
                        log.writeSensorlog(item.d_guid, "currentFlow", UtilsNumber.GetNumberForLength(currentFlow, 2).ToString(), "当前流量L");
                        log.writeSensorlog(item.d_guid, "totalFlow", UtilsNumber.GetNumberForLength(totalFlow, 2).ToString(), "历史流量L");
                    }
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

    }

}
